#include <Lucnx/task.h>
#include <Lucnx/io.h>
#include <Lucnx/debug.h>
#include <Lucnx/interrupt.h>
#include <Lucnx/device.h>

u32 all_ticks;

void pit_handler()
{
    task_t *cur = running_task();
    all_ticks++;
    if (cur->counter)
    {
        cur->counter--;
        cur->jiffies++;
        return;
    }
    schedule();
}

void timer_init()
{
    u16 speed = 1193180 / 100; // PIT HZ 算法
    outb(0x43, 0b00110100);
    outb(0x40, speed);
    outb(0x40, speed >> 8);

    set_pic_irq(0x20, true);
    register_handler(0x20, pit_handler);
    INFOK("INFO", "Timer init done");

    device_install("timer", NULL, NULL, NULL, NULL, DEV_DEFAULT, 0);
}